// 导入express模块
const express = require('express');
// 导入连接池模块
const pool = require('../pool');
// 创建路由器对象
const router = express.Router();
// 用户相关路由
// 用户注册
router.post('/reg', (req, res) => {
  // 获取浏览器端传入的参数
  let obj = req.body;
  // 定义一个code状态码，当必填项为空时，响应对应的错误
  let code = 400;
  // 判断传入的数据是否为空
  for (var k in obj) {
    code++;
    if (!obj[k]) {
      res.send({
        code: code,
        msg: `${k} required`
      });
      return;
    }
  }
  // 使用添加用户的sql语句
  let sql = 'INSERT INTO xz_user SET ?';
  pool.query(sql, [obj], (err, result) => {
    if (err) {
      res.send({
        code: 500,
        msg: `server error`
      });
      return;
    }
    !result.affectedRows ? res.send({ code: 201, msg: '添加失败' }) : res.send({ code: 200, msg: '添加成功' });
  });
});
// 用户登录
router.post('/login', (req, res) => {
  let obj = req.body;
  // sql根据uname和pwd查询数据库是否可以查询到
  let sql = "SELECT uid FROM xz_user WHERE uname=? AND upwd = ?";
  pool.query(sql, [obj.uname, obj.upwd], (err, result) => {
    if (err) { res.send({ code: 500, msg: `sever error` }) };
    !result.length ? res.send({ code: 201, msg: `用户不存在` }) : res.send({ code: 200, msg: `登录成功` });
  });
});
// 修改用户信息
router.put('/update/:uid', (req, res) => {
  // 用户的id
  let $uid = req.params.uid;
  // 用户传递的需要修改的信息
  let obj = req.body;
  // sql修改用户信息
  let sql = "UPDATE xz_user set ? WHERE uid=?";
  pool.query(sql, [obj, $uid], (err, result) => {
    if (err) { res.send({ code: 500, msg: 'server error' }); return };
    !result.affectedRows ? res.send({ code: 201, msg: '修改失败' }) : res.send({ code: 200, msg: '修改成功' });
  });
});
// 删除用户
router.delete('/deluser/:uid', (req, res) => {
  let $uid = req.params.uid;
  // sql语句，根据uid来删除用户
  let sql = 'DELETE FROM xz_user WHERE uid = ?';
  pool.query(sql, [$uid], (err, result) => {
    if (err) { res.send({ code: 500, msg: 'server error' }); return };
    !result.affectedRows ? res.send({ code: 201, msg: '删除失败' }) : res.send({ code: 200, mas: '删除成功' });
  });
});
// 查询用户列表
router.get('/userlist/:page/:count', (req, res) => {
  // 获取所有用户的信息
  // 每页5条信息
  let $page = parseInt(req.params.page);
  let $count = parseInt(req.params.count);
  // start=(当前的页码-1)*count;
  let start = ($page - 1) * $count;
  let sql = 'SELECT uid,uname,email,phone FROM xz_user LIMIT ?,?';
  pool.query(sql, [start, $count], (err, result) => {
    if (err) { res.send({ code: 500, msg: 'server error' }); return };
    !result.length ? res.send({ code: 201, msg: '没有更多了' }) : res.send({ code: 200, mas: '查询成功', date: result });
  });
});
// 根据id查询指定用户
router.get('/quser/:uid', (req, res) => {
  // 根据指定的uid查询特定的用户信息
  let $uid = req.params.uid;
  // sql语句
  let sql = 'SELECT * FROM xz_user WHERE uid = ?';
  pool.query(sql, [$uid], (err, result) => {
    if (err) { res.send({ code: 500, msg: 'server error' }); return };
    !result.length ? res.send({ code: 201, msg: '查无此人' }) : res.send({ code: 200, msg: '查询成功', data: result })
  });
});
// 导出用户路由器
module.exports = router;